﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Gollie.Mail;
using MySQL.Db;

namespace Gollie.Ajax
{
	public class ResetWW : AjaxResult
	{
		public ResetWW() : base(null) { }

		public ResetWW(AjaxArg arg)
			: base(arg)
		{

		}

		protected override void Init(AjaxArg ajaxArg)
		{
			UserInfo userInfo = null;

			try
			{
				bool ok = (ajaxArg.tokenUser.Length <= 16);
				if (ok)
				{
					userInfo = UserInfo.GetUserInfo(ajaxArg.tokenUser);
					if (userInfo == null)
						ok = false;
					else
						this.ChangePassword(userInfo);
				}

				if (!ok)
				{
					this.ErrorCode = 4;
					throw new Exception("Gebruiker niet gevonden");
				}
			}
			catch (Exception e)
			{
				if (this.ErrorCode == 0)
					this.ErrorCode = 99;

				this.ErrorMessage = e.Message;
			}
		}

		private void ChangePassword(UserInfo userInfo)
		{
			string newPwd = Hash.GetRandomPassword();
			string hashed = Hash.GetHash(newPwd);

			int success = Database.Queries.NewPassword(userInfo.Gebruikersnaam, hashed);

			MailClient.Queue(new EMail
			{
				Name = "changepassword",
				Recipients = userInfo.Email,
				Args = new Dictionary<string, string>()
				{
											{ "{pwd}", newPwd },
											{ "{aanhef}", userInfo.MailAanhef },
										    
				}
			});
		}
	}
}